﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.UI.WebControls;

using CharityGamesOnline.Modules.Common;
using CharityGamesOnline.Modules.Game;
using CharityGamesOnline.Modules.Event;
using ISGPayment;
using Telerik.Web.UI;

namespace CharityGamesOnline.Modules.Account
{
    public partial class PaymentSendRequest : CGOBase
    {
        private int gameEnrollmentID;
        private int paymentID;
        private string triggerCssName = "paynow";
        
        public int GameEnrollmentID
        {
            get
            {
                if (gameEnrollmentID == 0)
                {
                    if (Request.QueryString["GameEnrollmentID"] != null)
                    {
                        gameEnrollmentID = Int32.Parse(Request.QueryString["GameEnrollmentID"]);
                    }
                }
                return gameEnrollmentID;
            }
        }

        public int PaymentID
        {
            get
            {
                if (paymentID == 0)
                {
                    if (Request.QueryString["PaymentID"] != null)
                    {
                        paymentID = Int32.Parse(Request.QueryString["PaymentID"]);
                    }
                }
                return paymentID;
            }
        }

        public string TriggerCssName
        {
            get
            {
                return triggerCssName;
            }
            set
            {
                triggerCssName = value;
            }
        }

        public int PayListTabID
        {
            get
            {
                if (!Null.IsNull(Settings["PayListTabID"]))
                {
                    return Int32.Parse(Settings["PayListTabID"].ToString());
                }
                else
                    return TabId;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                RegisterScripts();
                if (Settings["PayConfirmContent"]!=null)
                    ltPayAmountSelection.Text = Server.HtmlDecode(Settings["PayConfirmContent"].ToString());
                if (Settings["PayConfirmContent"] != null)
                    ltPayConfirm.Text = Server.HtmlDecode(Settings["PayConfirmContent"].ToString());
                if (Settings["GoToPayContent"] != null)
                    ltGoToPay.Text = Server.HtmlDecode(Settings["GoToPayContent"].ToString());
                if (Settings["PopupContent"]!=null)
                    ltPopupContent.Text = Server.HtmlDecode(Settings["PopupContent"].ToString());
                
                if (!Page.IsPostBack)
                {                    
                    if (GameEnrollmentID > 0)
                    {
                        BindPaymentData();
                    }
                    else if (PaymentID > 0)
                    {
                        BindGoToPayData();                        
                    }
                    else
                    {
                        BindPayAmountData();
                    }
                }
            }

            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void btnSelect_Click(object sender, ImageClickEventArgs e)
        {
            lbEventName.Text = Localization.GetString("NoRelatedEvent",LocalResourceFile);
            lbGameName.Text = Localization.GetString("NoRelatedGame", LocalResourceFile);
            lbPayAmount.Text = ddlPayAmount.SelectedItem.Text;
            hidPayAmount.Value = ddlPayAmount.SelectedValue;
            hidEventID.Value = string.Empty;
            HidePanels();
            pnlPayConfirm.Visible = true;
        }

        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            PaymentController ctrlPayment = new PaymentController();
            decimal paymentAmount = Decimal.Parse(hidPayAmount.Value);
            //get the related unpaid payment id according to enrollment
            if (GameEnrollmentID > 0)
            {
                List<PaymentInfo> listPayment = ctrlPayment.GetPayments(PortalId, UserId, GameEnrollmentID, 0);
                foreach (PaymentInfo objPayment in listPayment)
                {
                    if (objPayment.StatusID == (int)PaymentInfo.STATUS.WaitingForPay || objPayment.StatusID == (int)PaymentInfo.STATUS.Processing)
                    {
                        paymentID = objPayment.PaymentID; 
                    }
                }
            }
            //if no, maybe not related to enrollment or it is new for a enrollment, create a new payment
            if (paymentID == 0)
            {
                PaymentInfo objPayment = new PaymentInfo();
                objPayment.PortalID = PortalId;
                objPayment.UserID = UserId;
                objPayment.Amount = paymentAmount;
                objPayment.EnrollmentID = GameEnrollmentID;
                objPayment.StatusID = (int)PaymentInfo.STATUS.WaitingForPay;
                paymentID = ctrlPayment.SavePayment(objPayment);
            }
            BindGoToPayData();
        }

        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            if (GameEnrollmentID > 0)
            {
                if (!Null.IsNull(Settings["EventDetailTabID"]))
                {
                    Response.Redirect(Globals.NavigateURL(Int32.Parse(Settings["EventDetailTabID"].ToString()), string.Empty, "EventID=" + hidEventID.Value));
                }
                else
                {
                    Response.Redirect(Globals.NavigateURL(PayListTabID), true); 
                }                
            }
            else
            {
                Response.Redirect(Globals.NavigateURL(PayListTabID), true);
            }
        }

        private void BindPaymentData()
        {
            HidePanels();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            EventController ctrlEvent = new EventController();
            GameController ctrlGame = new GameController();
            GameEnrollmentInfo objEnroll = ctrlEnroll.GetEnrollment(PortalId, GameEnrollmentID);

            if (!Null.IsNull(objEnroll) && objEnroll.UserID == UserId)
            {
                pnlPayConfirm.Visible = true;
                GameInfo objGame = ctrlGame.GetGame(objEnroll.GameID);
                EventInfo objEvent = ctrlEvent.GetEvent(PortalId, objEnroll.EventID);
                lbEventName.Text = objEvent.Name;
                lbGameName.Text = objGame.Name;
                lbPayAmount.Text = string.Format(Localization.GetString("PayAmountFormat", LocalResourceFile), objEnroll.EnrollFee);
                hidPayAmount.Value = objEnroll.EnrollFee.ToString();
                hidEventID.Value = objEvent.EventID.ToString();
            }
            else
            {
                lbMessage.Text = string.Format(Localization.GetString("errorPaymentUserNotMatch", LocalResourceFile), UserInfo.Username, objEnroll.UserName); 
            }
        }

        private void BindPayAmountData()
        {
            HidePanels();
            lbMessage.Text = Localization.GetString("errorNotLinkToEvent", LocalResourceFile);
            //pnlPayAmountSelection.Visible = true;
            //decimal minPayAmount = Decimal.Parse(Localization.GetString("minPayAmount", LocalResourceFile));
            //decimal maxPayAmount = Decimal.Parse(Localization.GetString("maxPayAmount", LocalResourceFile));
            //decimal unitPayAmount = Decimal.Parse(Localization.GetString("unitPayAmount", LocalResourceFile));
            //decimal payAmount = minPayAmount;
            //string strFormat = Localization.GetString("PayAmountFormat", LocalResourceFile);
            //while (payAmount <= maxPayAmount)
            //{
            //    ddlPayAmount.Items.Add(new RadComboBoxItem(string.Format(strFormat, payAmount), payAmount.ToString()));
            //    payAmount = payAmount + unitPayAmount;
            //}
        }

        private void BindGoToPayData()
        {
            HidePanels();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            GameController ctrlGame = new GameController();
            PaymentController ctrlPayment = new PaymentController();
            PaymentInfo objPayment = ctrlPayment.GetPayment(PortalId, PaymentID);

            if (objPayment.StatusID == (int)PaymentInfo.STATUS.WaitingForPay || objPayment.StatusID == (int)PaymentInfo.STATUS.Processing)
            {
                pnlGoToPay.Visible = true;
                lbPaymentID.Text = PaymentID.ToString();
                linkPayLater.HRef = Globals.NavigateURL(PayListTabID);
                linkPayNow.HRef = ResolveUrl("Pay.aspx") + "?PaymentID=" + PaymentID.ToString();
                linkPayNow.Attributes.Add("onclick", string.Format("jQueryCS('#{0}').jqmShow()", popupDialog.ClientID));

                linkComplete.HRef = Globals.NavigateURL(PayListTabID);
                if (!Null.IsNull(Settings["GameDetailTabID"]) && GameEnrollmentID > 0)
                {
                    GameEnrollmentInfo objEnroll = ctrlEnroll.GetEnrollment(PortalId, GameEnrollmentID);
                    if (!Null.IsNull(objEnroll))
                    {                        
                        linkComplete.HRef = Globals.NavigateURL(Int32.Parse(Settings["GameDetailTabID"].ToString()), string.Empty, "EventID=" + objEnroll.EventID.ToString());
                    }
                }
            }
            else
            {                
                lbMessage.Text = string.Format( Localization.GetString("errorPaymentNotActive", LocalResourceFile),objPayment.PaymentStatus);
            }
        }

        private int SavePayment(decimal payAmount, int enrollID)
        {
            int paymentID = 0;
            PaymentController ctrlPayment = new PaymentController();
            PaymentInfo objPayment = new PaymentInfo();
            objPayment.PortalID = PortalId;
            objPayment.UserID = UserId;
            objPayment.Amount = payAmount;
            objPayment.EnrollmentID = enrollID;
            objPayment.StatusID = (int)PaymentInfo.STATUS.WaitingForPay;
            paymentID = ctrlPayment.SavePayment(objPayment);            
            return paymentID;
        }

        private void HidePanels()
        {
            pnlPayAmountSelection.Visible = false;
            pnlPayConfirm.Visible = false;
            pnlGoToPay.Visible = false;
        }
        private void RegisterScripts()
        {
            string csName = string.Empty;
            string csText = string.Empty;
            Type csType = System.Reflection.MethodBase.GetCurrentMethod().GetType();
            
            csName = "cs.jquery";
            csText = "<script src=\"" + ResolveUrl("Script/jquery-1.3.2.min.cs.js") + "\" type=\"text/javascript\"></script>";

            if (!Page.ClientScript.IsClientScriptBlockRegistered(csName))
            {
                Page.ClientScript.RegisterClientScriptBlock(csType, csName, csText);
            }

            csName = "cs.jquery.popup";
            csText = "<script src=\"" + ResolveUrl("Script/jqModal.js") + "\" type=\"text/javascript\"></script>";

            if (!Page.ClientScript.IsClientScriptBlockRegistered(csName))
            {
                Page.ClientScript.RegisterClientScriptBlock(csType, csName, csText);
            }
        }
    }
}